import tkinter as tk
from tkinter import ttk
import tkinter.messagebox
import linecache
import numpy as np



window = tk.Tk()
window.title('英语单词想你了，你快吐了')
window.geometry('600x600')

canvas = tk.Canvas(window,heigh=200,width=500)
image_file = tk.PhotoImage(file='欢迎光临.gif')
image = canvas.create_image(50, 10, anchor='nw', image=image_file)
x0, y0, x1, y1 = 50, 50, 80, 80
canvas.pack(side='top')

tk.Label(window, text='类型: ').place(x=150, y=200)
test_type = tk.StringVar()
r1 = tk.Radiobutton(window, text='中->英',value='英', variable= test_type)
r1.select()
r1.place(x=210,y=200)
r2 = tk.Radiobutton(window,text='英->中',value='中', variable= test_type)
r2.deselect()
r2.place(x=210,y=230)


tk.Label(window, text='单词数量: ').place(x=150, y=280)
word_count = tk.StringVar()
comboxlist = ttk.Combobox(window, textvariable=word_count)
comboxlist['values'] = ('5','10','15','20','25', '50','100')
comboxlist.current(0)
comboxlist.place(x=210,y=280)

tk.Label(window, text='词汇库: ').place(x=150, y=330)
word_voc = tk.StringVar()
comboxlist = ttk.Combobox(window, textvariable=word_voc)
comboxlist['values'] = ('小学','PET')
comboxlist.current(1)
comboxlist.place(x=210, y=330)

tk.Label(window, text='难易程度: ').place(x=150, y=380)
test_level = tk.StringVar()
comboxlist = ttk.Combobox(window, textvariable=test_level)
comboxlist['values'] = ('菜鸟','平民','专家')
comboxlist.current(0)
comboxlist.place(x=210, y=380)

tk.Label(window, text='抽取方式: ').place(x=150, y=430)
choise_type = tk.StringVar()
comboxlist = ttk.Combobox(window, textvariable=choise_type)
comboxlist['values'] = ('随机抽','从某个字母开始抽','只在某个字母范围内抽')
comboxlist.current(0)
comboxlist.place(x=210, y=430)

tk.Label(window, text='字母（如选“随机抽”不填此项）: ').place(x=150, y=480)
choise_letter = tk.StringVar()
comboxlist = ttk.Combobox(window, textvariable=choise_letter)
comboxlist['values'] = ('a','b','c','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
comboxlist.current(0)
comboxlist.place(x=320, y=480)

def get_line_number(test_level, choise_type, choise_letter, line_array, total_number):
    find_same = True
    while(find_same == True):
        line_number = np.random.randint(1, total_number)
        find_same = False
        for index in range(line_array.shape[0]):
            if (line_array[index] == line_number):
                find_same = True
                break

        if (find_same == False):
            line_text = linecache.getline('./PET.txt', line_number)
            if ((len(line_text) - 1) == 1):
                find_same = True
                continue

            first_leter = line_text[0].lower()
            if ((choise_type.get() == '从某个字母开始抽') and (first_leter < choise_letter.get())):
                find_same = True
                continue
            elif ((choise_type.get() == '只在某个字母范围内抽') and (first_leter != choise_letter.get())):
                find_same = True
                continue



            find_index = line_text.find('(')
            line_text = line_text[0:find_index]
            if (test_level.get() == '菜鸟') and (len(line_text)>=10):
                find_same = True
                continue
            elif (test_level.get() == '专家') and (len(line_text)<15):
                find_same = True
                continue

    return line_number

def get_hint_text(test_type, file_name, line_index):
    line_text = linecache.getline(file_name, line_index)
    if (test_type.get() == '英'):
        first_letter = line_text[0]
        find_index = line_text.find('(')
        line_text = line_text[find_index:]
        line_text = line_text + first_letter + '_ '
    else:
        find_index = line_text.find('(')
        find_index2 = line_text.find(')')
        first_letter = line_text[find_index2 + 2]
        line_text = line_text[0:find_index]
        line_text = line_text + '\n' + first_letter + '_ '
    return line_text

def get_answer_text(test_type, file_name, line_index):
    line_text = linecache.getline(file_name, line_index)
    if (test_type.get() == '英'):
        find_index = line_text.find('(')
        line_text = line_text[0:find_index]
    else:
        find_index = line_text.find(')')
        line_text = line_text[find_index+2:]
    return line_text

def check_answer_correctness(answer_input, test_type, file_name, line_index):
    answer_text = get_answer_text(test_type, file_name, line_index)
    answer_text = answer_text.rstrip('\n')
    answer_input = answer_input.strip()
    if (answer_input == answer_text):
        return True
    else:
        return False

def start():
    print("test type:", test_type.get())
    print("word count:", word_count.get())
    print("word vocabulary:", word_voc.get())
    print("test level:", test_level.get())
    print("choice type:", choise_type.get())
    print("choice letter:", choise_letter.get())
    #line_text = linecache.getline('./PET.txt', 600)

    #
    # Get the total line number
    #
    line_total = 0
    for line in open("./PET.txt", encoding='utf-8'):
        line_total += 1

    line_index_array = np.zeros(int(word_count.get()))
    for index in range(line_index_array.shape[0]):
        line_index_array[index] = get_line_number(test_level, choise_type, choise_letter, line_index_array, line_total)
        print(line_index_array[index])

    answer_string_array = []
    result_array = []
    for index in range(line_index_array.shape[0]):
        answer_string_array.append("")
        result_array.append(False)

    window.wm_state('iconic')
    window_question = tk.Toplevel(window)
    window_question.geometry('400x400')
    window_question.title('答题时间')
    title_lable = tk.StringVar()
    title_tklable = tk.Label(window_question, textvariable=title_lable,width=30)
    title_tklable.place(x=80, y=10)
    hint_lable = tk.StringVar()
    tk.Label(window_question, textvariable=hint_lable, width=30).place(x=80, y=100)
    answer_string = tk.StringVar()
    entry_answer = tk.Entry(window_question,bg='light yellow',textvariable=answer_string,width=50)
    entry_answer.place(x=20, y=200)

    global cur_index
    cur_index = 1
    global is_submitted
    is_submitted = False
    title_string = str(cur_index)+'/'+ word_count.get()
    title_lable.set(title_string)
    line_text = get_hint_text(test_type, './PET.txt', int(line_index_array[cur_index-1]))
    hint_lable.set(line_text)
    answer_string.set(answer_string_array[cur_index-1])

    def prev():
        global cur_index
        global is_submitted
        answer_string_array[cur_index - 1] = answer_string.get()
        result_array[cur_index - 1] = check_answer_correctness(answer_string_array[cur_index - 1], test_type, './PET.txt', int(line_index_array[cur_index - 1]))
        cur_index-=1
        if (cur_index <= 0):
            cur_index = 1
        title_string = str(cur_index) + '/' + word_count.get()
        title_lable.set(title_string)
        line_text = get_hint_text(test_type, './PET.txt', int(line_index_array[cur_index - 1]))
        hint_lable.set(line_text)
        answer_string.set(answer_string_array[cur_index - 1])
        if is_submitted:
            if result_array[cur_index - 1]:
                title_tklable.config(bg='green')
            else:
                title_tklable.config(bg='red')

    def next():
        global cur_index
        answer_string_array[cur_index - 1] = answer_string.get()
        result_array[cur_index - 1] = check_answer_correctness(answer_string_array[cur_index - 1], test_type, './PET.txt', int(line_index_array[cur_index - 1]))
        cur_index += 1
        if (cur_index > int(word_count.get())):
            cur_index = int(word_count.get())
        title_string = str(cur_index) + '/' + word_count.get()
        title_lable.set(title_string)
        line_text = get_hint_text(test_type, './PET.txt', int(line_index_array[cur_index - 1]))
        hint_lable.set(line_text)
        answer_string.set(answer_string_array[cur_index - 1])
        if is_submitted:
            if result_array[cur_index - 1]:
                title_tklable.config(bg='green')
            else:
                title_tklable.config(bg='red')

    def done():
        global cur_index
        global is_submitted
        answer_string_array[cur_index - 1] = answer_string.get()
        result_array[cur_index - 1] = check_answer_correctness(answer_string_array[cur_index - 1], test_type,
                                                               './PET.txt', int(line_index_array[cur_index - 1]))
        right_number = 0
        for index in range(int(word_count.get())):
            if (result_array[index] == True):
                right_number+=1
        final_score = 100 // int(word_count.get()) * right_number
        message_text1 = "correct:" + str(right_number) + " wrong:" + str(int(word_count.get()) - right_number)
        message_text2 = "score:" + str(final_score)
        tk.messagebox.showinfo('Test Result', message_text1+"\n"+message_text2)
        is_submitted = True
        answer_button.pack()
        answer_button.place(x=50, y=300, anchor='nw')
        if is_submitted:
            if result_array[cur_index - 1]:
                title_tklable.config(bg='green')
            else:
                title_tklable.config(bg='red')

    def answer():
        global cur_index
        answer_text = get_answer_text(test_type, './PET.txt', int(line_index_array[cur_index - 1]))
        tk.messagebox.showinfo('Correct Answer:\n', answer_text + "\n")

    b1 = tk.Button(window_question, bg='red',text='上一个', width=7, height=1, command=prev).place(x=100, y=300, anchor='nw')
    b2 = tk.Button(window_question, bg='red',text='下一个', width=7, height=1, command=next).place(x=175, y=300, anchor='nw')
    b3 = tk.Button(window_question, bg='yellow',text='完成', width=5, height=1, command=done).place(x=250, y=300, anchor='nw')
    answer_button=tk.Button(window_question, bg='green', text='答案', width=3, height=1, command=answer)
    answer_button.pack_forget()


b = tk.Button(window, text='开始', width=5, height=1, command=start).place(x=250, y=530, anchor='nw')


window.mainloop()